<template>
	<view class="content">
		<u--text :text="word"></u--text>
		<view style="height: 5px;"></view>
		<u--text :text="wordMessage"></u--text>
		
		<view style="height: 50px;"></view>
		<u-row customStyle="margin-bottom: 10px">
			<u-col span="5">
				<u-button text="英" type="warning" @click="playEn" size="small"></u-button>
			</u-col>
			<u-col span="2"></u-col>
			<u-col span="5">
				<u-button text="美" type="warning" @click="playUs" size="small"></u-button>
			</u-col>
		</u-row>
						
		<u-button text="下一个" type="success" @click="showTitle"></u-button>
		<view style="height: 10px;"></view>
		<u-button text="随机获取" type="success" @click="showRandWord"></u-button>
		<view style="height: 10px;"></view>
		<u-button text="自动播放" type="success" @click="autoPlay"></u-button>
		<view style="height: 10px;"></view>
		<u-button text="停止播放" type="success" @click="stopPlay"></u-button>
		
	</view>
</template>

<script>
	export default {
		data() {
			return {
				word:"",
				wordMessage:"",
				wordId:0,
				autoPlayBool:false,
				autoPlayObj:null
			};
		},
		onShow() {
			this.showTitle()
		},
		methods:{
			playUs(){
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = 'https://dict.youdao.com/dictvoice?audio='+this.word+'&type=2';
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
			},
			playEn(){
				const innerAudioContext = uni.createInnerAudioContext();
				innerAudioContext.autoplay = true;
				innerAudioContext.src = 'https://dict.youdao.com/dictvoice?audio='+this.word+'&type=1';
				innerAudioContext.onPlay(() => {
				  console.log('开始播放');
				});
				innerAudioContext.onError((res) => {
				  console.log(res.errMsg);
				  console.log(res.errCode);
				});
			},
			showTitle(){
				this.wordId += 1;
				uni.$u.http.get('/api/word/info?id='+this.wordId, {}).then(res => {
					this.word = res.data.data.word
					this.wordMessage = res.data.data.message
					this.playUs()
				}).catch(err => {
				
				})
			},
			showRandWord(){
				uni.$u.http.get('/api/word/randomWord', {}).then(res => {
					this.word = res.data.data.word
					this.wordMessage = res.data.data.message
					this.playUs()
				}).catch(err => {
				
				})
			},
			autoPlay(){
				if(this.autoPlayBool){
					return;
				}
				this.autoPlayBool = true;
				var that = this;
				that.showRandWord();
				this.autoPlayObj = setInterval(function(){
				    that.showRandWord();
				}, 5000)
				
			},
			stopPlay(){
				if(!this.autoPlayBool){
					return;
				}
				clearInterval(this.autoPlayObj);
				this.autoPlayBool = false;
			}
		}
	};
</script>

<style>
	.content{
		padding: 5px;
	}
</style>
